//
//  MusicViewController.m
//  Blue-toothLight
//
//  Created by mazg on 15/6/20.
//  Copyright (c) 2015年 mazg. All rights reserved.
//

#import "MusicViewController.h"
#import "AudioTool.h"
#import <AudioToolbox/AudioToolbox.h>
#import <MediaPlayer/MediaPlayer.h>


@interface MusicViewController ()<AVAudioPlayerDelegate>{
    UIView *view1;
    UIView *view2;
    MusicModel *lastModel;//上次播放的音乐
    NSInteger playIndex;//当前播放的音乐索引
    NSTimer *progressT;//跟新进度条的定时器
    NSTimer *colorT;//跟新颜色的定时器
    UISlider *volumeViewSlider;//获取系统声音大小的slider
    CGFloat mobileVol;//获取到的系统音量
}

@end

@implementation MusicViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self loadInitialView];
    
    //加载歌曲
    self.musicList=[MusicModel allMusicsFromLocal];
    
    //获取系统音量
    [self getVolumeLevel];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(volumeChanged:)
                                            name:@"AVSystemController_SystemVolumeDidChangeNotification"
                                            object:nil];
}

//获取到的系统音量
-(float) getVolumeLevel
{
    MPVolumeView *slide =[MPVolumeView new];
   
    for(UIView*view in [slide subviews])
    {
        if([[[view class] description] isEqualToString:@"MPVolumeSlider"])
        {
            volumeViewSlider =(UISlider*) view;
        }
    }
    mobileVol =[volumeViewSlider value];
    return mobileVol;
}

//系统音量变化后调用的方法
-(void)volumeChanged:(NSNotification *)notification {
    mobileVol=[[[notification userInfo] objectForKey:@"AVSystemController_AudioVolumeNotificationParameter"] floatValue];
    [volumeViewSlider setValue:mobileVol animated:YES];
}

//加载初始视图
-(void)loadInitialView{
    view1=[[[NSBundle mainBundle]loadNibNamed:@"MusicView1" owner:self options:nil] lastObject];
    view1.frame=self.view.frame;
    [self.view addSubview:view1];
    view1.hidden=NO;
    
    view2=[[[NSBundle mainBundle]loadNibNamed:@"MusicView2" owner:self options:nil] lastObject];
    view2.frame=self.view.frame;
    [self.view addSubview:view2];
    view2.hidden=YES;
    
    _superBtn.layer.cornerRadius=5;
    _superBtn.layer.borderColor=[UIColor blueColor].CGColor;
    _superBtn.layer.borderWidth=1.0f;
    _superBtn.backgroundColor=[UIColor blackColor];
    
    _downBtn.layer.cornerRadius=5;
    _downBtn.layer.borderColor=[UIColor blueColor].CGColor;
    _downBtn.layer.borderWidth=1.0f;
    _downBtn.backgroundColor=[UIColor blackColor];
    
    _flashBtn.layer.cornerRadius=5;
    _flashBtn.layer.borderColor=[UIColor blueColor].CGColor;
    _flashBtn.layer.borderWidth=1.0f;
    _flashBtn.backgroundColor=[UIColor blackColor];
    
    _smoothBtn.layer.cornerRadius=5;
    _smoothBtn.layer.borderColor=[UIColor blueColor].CGColor;
    _smoothBtn.layer.borderWidth=1.0f;
    _smoothBtn.backgroundColor=[UIColor blackColor];
    
    self.tableView.backgroundColor=[UIColor clearColor];
    self.tableView.rowHeight=60;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)toggleAction1:(id)sender {
    view2.hidden=NO;
    view1.hidden=YES;
}

- (IBAction)toggleAction2:(id)sender {
    view1.hidden=NO;
    view2.hidden=YES;
}

- (IBAction)sliderChanged:(id)sender {
    self.player.currentTime=self.slider.value;
}

- (IBAction)flashBtnPressed:(id)sender {
    
}
- (IBAction)smoothBtnPressed:(id)sender {
    
}

//上一首歌曲
- (IBAction)perviousMusic:(id)sender {
    [self.player pause];
    playIndex--;
    if (playIndex==-1) {
        playIndex=0;
    }
    MusicModel *model=self.musicList[playIndex];
    
    [self playWithSelectedModel:model];
    
    NSIndexPath *path=[NSIndexPath indexPathForRow:playIndex inSection:0];
    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

//下一首歌曲
- (IBAction)nextMusic:(id)sender {
    [self.player pause];
    playIndex++;
    if (playIndex==self.musicList.count) {
        playIndex=self.musicList.count-1;
    }
    MusicModel *model=self.musicList[playIndex];
    [self playWithSelectedModel:model];
    
    NSIndexPath *path=[NSIndexPath indexPathForRow:playIndex inSection:0];
    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
}

- (IBAction)playMusic:(id)sender {
    UIButton *btn=sender;
    if (self.player.isPlaying) {
        [self.player pause];
        btn.selected=YES;
    }
    else{
        [self.player play];
        btn.selected=NO;
    }
}

-(void)updateProgress:(NSTimer *)timer{
    self.slider.value=self.player.currentTime;
    self.timeLabel.text=[self timeFormatted:(int)self.player.currentTime];
}

- (NSString *)timeFormatted:(int)totalSeconds
{
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    return [NSString stringWithFormat:@"%02d:%02d:%02d",hours, minutes, seconds];
}

-(void)getNewColorWithPlayer:(NSTimer *)timer{
    
    [self.player updateMeters];
    static float last = 0;
    float cur = [self.player averagePowerForChannel:1];
    float cha = cur - last;
    last = cur;
    static int lastH = 0;
    if(cur > -30 && cur <-1)
    {
        //根据差值 改变颜色偏转角度
        int h = lastH+ABS(cha*10);
        if(h>360)
        {
            h-=360;
        }
        // 根据根据音量决定亮度和饱和度 cur 范围大概-30~0
        //音量越大，颜色越深，透明度越大
        if (mobileVol<0.5) {
            mobileVol=0.5;
        }
        int v = 255 * ((cur +30)/30.0)*mobileVol;
        UIColor *color= [UIColor colorWithHue:h/360.0 saturation:v/255.0 brightness:v/255.0 alpha:v/255.0];
        CGFloat r,g,b,w;
        [color getRed:&r green:&g blue:&b alpha:&w];
    
        NSLog(@"v:%i  W:%f",v,w);
        
        NSArray *perArr=[self getCurrentPeripheralArr];
        //        for (CBPeripheral *cbp in perArr) {
        //            UIColor *newColor=[UIColor colorWithRed:r+(arc4random()%10)/100.0 green:g+(arc4random()%10)/100.0  blue:b+(arc4random()%10)/100.0  alpha:w+(arc4random()%10)/100.0];
        //            [self.colorInstance changeColorWithPeripheral:cbp ToTarget:newColor];
        //        }
        for (int i=0;i<perArr.count;i++) {
            
            UIColor *newColor=[UIColor colorWithRed:r green:g  blue:b  alpha:1-w-arc4random()%10/40.0f];
            [self.colorInstance changeColorWithPeripheral:perArr[i] ToTarget:newColor];
            
            
//            [self.colorInstance changeColorWithPeripheral:perArr[i] ToTarget:[UIColor colorWithRed:0 green:0 blue:0 alpha:0] afterDelay:0.3];
            //            if (i==0) {
            //                self.textview1.backgroundColor=newColor;
            //            }
            //            else if (i==1) {
            //                self.testview2.backgroundColor=newColor;
            //            }
            //            else if (i==2) {
            //                self.testview3.backgroundColor=newColor;
            //            }
        }
        lastH = h;

    }
}



#pragma mark UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.musicList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier=@"cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.backgroundColor=[UIColor clearColor];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
    }
    cell.imageView.image=[UIImage imageNamed:@"palyingmusic@2x.png"];
    MusicModel *model=self.musicList[indexPath.row];
    cell.textLabel.text=model.title;
    cell.textLabel.textColor=[UIColor whiteColor];
    
    if (model.isSelected) {
        cell.accessoryType=UITableViewCellAccessoryCheckmark;
    }
    else{
        cell.accessoryType=UITableViewCellAccessoryNone;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MusicModel *model=self.musicList[indexPath.row];
    [self playWithSelectedModel:model];
}

-(void)playWithSelectedModel:(MusicModel *)model{
    [progressT invalidate];
    [colorT invalidate];
    model.isSelected=YES;
    
    self.slider.minimumValue=0;
    self.slider.maximumValue=model.playbackDuration;
    self.musicLabel.text=model.title;
    
    [self.player pause];
    self.player=[AudioTool playMusicWithUrl:model.songUrl];
    self.player.delegate=self;
    self.player.meteringEnabled = YES;
    
    NSInteger row=[self.musicList indexOfObject:model];
    playIndex=row;
    
    [NSThread detachNewThreadSelector:@selector(startTimer) toTarget:self withObject:nil];
    
    lastModel.isSelected=NO;
    lastModel=model;
    [self.tableView reloadData];
}

//非主线程开启timer
-(void)startTimer{
    progressT=[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateProgress:) userInfo:nil repeats:YES];
    
    colorT=[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(getNewColorWithPlayer:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] run];
}

#pragma mark AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [self nextMusic:nil];
}

@end
